package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.pcl;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.kafka.JFKafkaProducer;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.models.KafkaMessage;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.DateBranchHelper;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.base.enums.EPayType;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.base.models.OrderLogContent;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WXRefundOrder;
import com.gzhryc.shared_device.common.payment.services.WXPayOrderService;
import com.gzhryc.shared_device.common.payment.services.WXRefundOrderService;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.PayServiceFactory;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.order.RedisCacheManager;
import com.gzhryc.shared_device.oem.code.order.event.OrderFinishEvent;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrder;
import com.gzhryc.shared_device.oem.code.profit.dao.enums.BusinessOrderEnum;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLOrder;
import com.gzhryc.shared_device.pcl.code.dao.db.PCLOrderLog;
import com.gzhryc.shared_device.pcl.code.dao.enums.EPCLCostMode;
import com.gzhryc.shared_device.pcl.code.dao.enums.PCLOrderEnum;
import com.gzhryc.shared_device.pcl.code.services.PCLOrderLogService;
import com.gzhryc.shared_device.pcl.code.services.PCLOrderService;
import com.gzhryc.shared_device.pcl.code.services.dto.PCLOrderSearch;
import com.gzhryc.system.SysConstants;
import com.gzhryc.system.dao.db.Manager;
import org.apache.commons.lang3.time.DateUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

public class ChargingCableOrderController {

    static Logger log = Logger.getLogger(ChargingCableOrderController.class);

    @Route("/pcl/order/list.html")
    public String list(HttpServletRequest request) {
        request.setAttribute("payStateList", PCLOrderEnum.PayState.values());
        request.setAttribute("stateList", PCLOrderEnum.State.values());
        request.setAttribute("costModeList", EPCLCostMode.values());
        request.setAttribute("dateBranchItemList", DateBranchHelper.self().getYearDateBranchItems());
        return "/pcl/order/list.html";
    }

    @Route(value = "/pcl/order/list.data")
    public ListResult<PCLOrder> listData(HttpServletRequest request) {
        ListResult<PCLOrder> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        PCLOrderSearch search = WebUtils.getParameter(request, PCLOrderSearch.class);
        String searchDate = WebUtils.getString(request,"searchDate");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            search.setAgentId(loginUser.getId());
            try {
                if (StringTools.isNotBlank(searchDate)) {
                    String[] strings = searchDate.split(" - ");
                    if (strings.length == 2) {
                        Date startDate = DateUtils.parseDate(strings[0], "yyyy-MM-dd");
                        Date endDate = DateUtils.parseDate(strings[1], "yyyy-MM-dd");
                        search.setStartDate(startDate);
                        search.setEndDate(endDate);
                    }
                }
                Date dateBranch = new Date();
                if (StringTools.isNotBlank(search.getDateBranchId())) {
                    dateBranch = DateBranchHelper.getDateByItemId(search.getDateBranchId());
                }

                result.getBody().setTotal(PCLOrderService.self(dateBranch).countBySearch(search));
                List<PCLOrder> data = PCLOrderService.self(dateBranch).findBySearch(search, pageNo, pageLimit);
                if (data != null && data.size() > 0) {
                    result.setCode(DtoConstants.SUCCESS, null);
                    result.getBody().setData(data);
                }
            } catch (Exception e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route("/pcl/order/info.html")
    public String info(HttpServletRequest request) {
        String tradeNo = WebUtils.getString(request,"tradeNo");
        Date createDate = WebUtils.getDate(request,"createDate");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            if (createDate == null) {
                createDate = new Date();
            }
            PCLOrder deviceOrder = PCLOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getAgentId() != null && deviceOrder.getAgentId().equals(loginUser.getId())) {
                WebUtils.setAttribute(request, deviceOrder);
                if (EPayType.WXPay.index().equals(deviceOrder.getPayType())) {
                    WXPayOrder payOrder = WXPayOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getPayTradeNo());
                    if (payOrder != null) {
                        request.setAttribute("payOrder", payOrder);
                        List<WXRefundOrder> refundOrderList = WXRefundOrderService.self(deviceOrder.getCreateDate()).findByBusinessTradeNo(payOrder.getBusinessTradeNo());
                        request.setAttribute("refundOrderList", refundOrderList);
                    }
                }
            }
        }
        request.setAttribute("businessType", EBusinessType.PCL);
        return "/pcl/order/info.html";
    }

    @Route(value = "/pcl/order/operate/record/list.data")
    public ListResult<OrderLogContent.LogItem> logListData(HttpServletRequest request) {
        ListResult<OrderLogContent.LogItem> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        String tradeNo = WebUtils.getString(request,"tradeNo");
        Date createDate = WebUtils.getDate(request,"createDate");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null && StringTools.isNotBlank(tradeNo)) {
            if (createDate == null) {
                createDate = new Date();
            }
            PCLOrder deviceOrder = PCLOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getAgentId() != null && deviceOrder.getAgentId().equals(loginUser.getId())) {
                PCLOrderLog orderLog = PCLOrderLogService.self(createDate).getByTradeNo(tradeNo);
                if (orderLog != null && StringTools.isNotBlank(orderLog.getContent())) {
                    OrderLogContent logContent = JsonTools.fromJson(orderLog.getContent(), OrderLogContent.class);
                    if (logContent != null) {
                        result.setCode(DtoConstants.SUCCESS, null);
                        result.getBody().setData(logContent.getItems());
                    }
                }
            }
        }
        return result;
    }

    @Route("/pcl/order/operate/refund.html")
    public String refund(HttpServletRequest request) {
        String tradeNo = WebUtils.getString(request,"tradeNo");
        Date createDate = WebUtils.getDate(request,"createDate");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null && StringTools.isNotBlank(tradeNo)) {
            if (createDate == null) {
                createDate = new Date();
            }
            PCLOrder deviceOrder = PCLOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getAgentId() != null && deviceOrder.getAgentId().equals(loginUser.getId())) {
                request.setAttribute("refundMoneyStr", deviceOrder.getPayMoneyStr());
            }
        }
        return "/pcl/order/refund.html";
    }

    @Route(value = {"/pcl/order/operate/refund.do"})
    public AjaxResult doRefund(HttpServletRequest request, HttpSession session) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "撤销订单失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        Date createDate = WebUtils.getDate(request,"createDate");
        Double refundMoneyStr = WebUtils.getDouble(request,"refundMoneyStr");
        String refundNote = WebUtils.getString(request,"refundNote");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null && StringTools.isNotBlank(tradeNo)) {
            if (refundMoneyStr == null) {
                result.setMsg("请填写退款金额");
                return result;
            }
            if (StringTools.isBlank(refundNote)) {
                result.setMsg("请填写退款原因");
                return result;
            }
            if(createDate == null){
                createDate = new Date();
            }

            //检查分成
            BusinessOrder businessOrder = BusinessOrderService.self(createDate).getByTradeNo(tradeNo);
            if(businessOrder != null && (BusinessOrderEnum.DivideState.Finish.index().equals(businessOrder.getDivideState())
                    || BusinessOrderEnum.DivideState.CancelExecuting.index().equals(businessOrder.getDivideState()))){
                result.setMsg("订单已分成，请回滚分成后操作");
                return result;
            }

            try {
                PCLOrder deviceOrder = PCLOrderService.self(createDate).getByTradeNo(tradeNo);
                if(deviceOrder == null){
                    result.setMsg("未找到租借订单");
                    return result;
                }

                if (deviceOrder.getAgentId() != null && deviceOrder.getAgentId().equals(loginUser.getId())) {
                    Manager manager = WebUtils.getAttribute(session, SysConstants.SESSION_LOGIN_MANAGER, Manager.class);
                    OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                    operateInfo.setOperator(EOperatorType.Manager.index(), manager.getFullName());
                    operateInfo.setOperateNote(refundNote);

                    Integer refundMoney = NumberTools.changeMoney(refundMoneyStr);

                    int refundResult = PCLOrderService.self(deviceOrder.getCreateDate()).refund(deviceOrder, refundMoney, PayServiceFactory.self(), operateInfo);
                    if (refundResult > 0) {
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value = { "/pcl/order/operate/cancel.html" })
    public String cancel(HttpServletRequest request) {
        return "/pcl/order/cancel.html";
    }

    @Route(value = { "/pcl/order/operate/cancel.do" })
    public AjaxResult doCancel(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "撤销失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        Date createDate = WebUtils.getDate(request,"createDate");
        String note = WebUtils.getString(request, "note");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null && StringTools.isNotBlank(tradeNo)) {
            if (StringTools.isBlank(note)) {
                result.setMsg("请填撤销的原因");
                return result;
            }
            if(createDate == null){
                createDate = new Date();
            }

            //检查分成
            BusinessOrder businessOrder = BusinessOrderService.self(createDate).getByTradeNo(tradeNo);
            if(businessOrder != null && (BusinessOrderEnum.DivideState.Finish.index().equals(businessOrder.getDivideState())
                    || BusinessOrderEnum.DivideState.CancelExecuting.index().equals(businessOrder.getDivideState()))){
                result.setMsg("订单已分成，请回滚分成后操作");
                return result;
            }

            PCLOrder deviceOrder = PCLOrderService.self(createDate).getByTradeNo(tradeNo);
            if(deviceOrder == null){
                result.setMsg("未找到租借订单");
                return result;
            }

            if (deviceOrder.getAgentId() != null && deviceOrder.getAgentId().equals(loginUser.getId())) {
                Manager manager = WebUtils.getAttribute(request, SysConstants.LOGIN_MANAGER, Manager.class);
                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator(EOperatorType.Manager.index(), manager.getFullName());
                operateInfo.setOperateNote(note);

                Date cancelDate = new Date();

                try {
                    int cancelResult = PCLOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder, PayServiceFactory.self(), operateInfo);
                    if (cancelResult > 0) {
                        //清理缓存，避免定时器重复处理
                        RedisCacheManager.removeWorkingCDBDeviceOrder(deviceOrder.getTradeNo());
                        if (cancelResult == 2) {
                            deviceOrder = PCLOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                            //同步会员订单
                            MemberBusinessOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder.getTradeNo(),
                                    deviceOrder.getMoney(), deviceOrder.getPayMoney(), deviceOrder.getWalletMoney());
                            BusinessOrderService.self(deviceOrder.getCreateDate()).cancel(deviceOrder.getTradeNo(), cancelDate);
                        }
                        result.setCode(DtoConstants.SUCCESS, null);
                    }
                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }
        }
        return result;
    }

    @Route("/pcl/order/operate/finish.html")
    public String finish(HttpServletRequest request) {
        String tradeNo = WebUtils.getString(request,"tradeNo");
        Date createDate = WebUtils.getDate(request,"createDate");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null && StringTools.isNotBlank(tradeNo)) {
            if (createDate == null) {
                createDate = new Date();
            }
            PCLOrder deviceOrder = PCLOrderService.self(createDate).getByTradeNo(tradeNo);
            if (deviceOrder != null && deviceOrder.getAgentId() != null && deviceOrder.getAgentId().equals(loginUser.getId())) {
                request.setAttribute("payMoneyStr", deviceOrder.getPayMoneyStr());
            }
        }
        return "/pcl/order/finish.html";
    }

    @Route(value = { "/pcl/order/operate/finish.do" })
    public AjaxResult doFinish(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "完成失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        Date createDate = WebUtils.getDate(request,"createDate");
        Double payMoneyPrice = WebUtils.getDouble(request,"payMoneyStr");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null && StringTools.isNotBlank(tradeNo)) {
            if (payMoneyPrice == null) {
                result.setMsg("请填写支付金额");
                return result;
            }
            if(createDate == null){
                createDate = new Date();
            }

            PCLOrder deviceOrder = PCLOrderService.self(createDate).getByTradeNo(tradeNo);
            if(deviceOrder == null){
                result.setMsg("未找到租借订单");
                return result;
            }

            if (deviceOrder.getAgentId() != null && deviceOrder.getAgentId().equals(loginUser.getId())) {
                Manager manager = WebUtils.getAttribute(request, SysConstants.LOGIN_MANAGER, Manager.class);
                OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                operateInfo.setOperator(EOperatorType.Manager.index(), manager.getFullName());
                operateInfo.setOperateNote("后台客服操作完成订单");

                try {
                    int finishResult = PCLOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder, NumberTools.changeMoney(payMoneyPrice), PayServiceFactory.self(), operateInfo);
                    if (finishResult > 0) {
                        //清理缓存，避免定时器重复处理
                        RedisCacheManager.removeWorkingCDBDeviceOrder(deviceOrder.getTradeNo());
                        if (finishResult == 2) {
                            deviceOrder = PCLOrderService.self(deviceOrder.getCreateDate()).getByTradeNo(deviceOrder.getTradeNo());
                            //同步会员订单
                            MemberBusinessOrderService.self(deviceOrder.getCreateDate()).finish(deviceOrder.getTradeNo(), deviceOrder.getMoney(), deviceOrder.getPayMoney(),
                                    deviceOrder.getWalletMoney(),operateInfo);

                            JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                            if (producer != null) {
                                OrderFinishEvent event = new OrderFinishEvent(EBusinessType.PCL.index(), deviceOrder.getTradeNo(), deviceOrder.getCreateDate(), operateInfo);
                                KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_OrderFinish, JsonTools.toJson(event));
                                producer.send(kafkaMessage);
                            } else {
                                log.error("未初始化消息队列，订单{{0}}未触发完成事件", deviceOrder.getTradeNo());
                            }
                        }
                        result.setCode(DtoConstants.SUCCESS, null);
                    }

                } catch (LogicException e) {
                    result.setMsg(e.getMessage());
                }
            }
        }
        return result;
    }
}
